package com.idbk.chargestation.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.dtr.zxing.activity.CaptureActivity;
import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.charge.ActivityChargeList;
import com.idbk.chargestation.activity.charge.ActivityChargingAc;
import com.idbk.chargestation.activity.charge.ActivityChargingDc;
import com.idbk.chargestation.activity.charge.ActivityChoosePile;
import com.idbk.chargestation.activity.charge.ActivityDoubleGun;
import com.idbk.chargestation.activity.charge.ActivityLock;
import com.idbk.chargestation.activity.charge.ActivityMultiGun;
import com.idbk.chargestation.activity.charge.ActivitySingleGun;
import com.idbk.chargestation.activity.user.ActivityLogin;
import com.idbk.chargestation.activity.user.ActivityMyBooking;
import com.idbk.chargestation.api.APIForCharge;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonChargeInfo;
import com.idbk.chargestation.bean.JsonChargeRefresh;
import com.idbk.chargestation.bean.JsonPointPile;
import com.idbk.chargestation.bean.JsonQrScan;
import com.idbk.chargestation.bean.JsonUser;
import com.idbk.chargestation.dialog.DialogResult;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.Const;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.util.GsonUtils;

/**
 * 充电扫码界面
 *
 * @author lupc, zhx
 */
public class FragmentCharge extends Fragment implements OnClickListener {

    private final static String TAG = FragmentCharge.class.getSimpleName();
    private final static String TIP_CHARGING = "你当前正在充电，点此查看";
    private final static String TIP_BESPEAKING = "你有一个充电预约订单，点此查看";
    public final static int QR_CODE_REQUEST = 3033;
    private Context mContext;
    private View mBaseView;
    private String mPileSn;
    private TextView mTextTip;
    private DialogResult mDialog;
    private ProgressDialog mProgressDialog;
    private ProgressDialog mProgress;
    private StringRequest mRequest;
    private String mSn;
    //接受返回的信息，判断是否更改SharedPreferences的值
    private boolean isSame;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mBaseView = inflater.inflate(R.layout.fragment_charge, container, false);

        mContext = getActivity();

        setupView();

        return mBaseView;
    }

    private void setupView() {
        mTextTip = (TextView) mBaseView.findViewById(R.id.textview_charge_state_tip);
        //绑定监听器
        (mBaseView).findViewById(R.id.imageview_qrcode).setOnClickListener(this);
        //我的充电
        (mBaseView).findViewById(R.id.textview_mycharge).setOnClickListener(this);
        (mBaseView).findViewById(R.id.imageview_inputsn).setOnClickListener(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        //每隔10秒 请求一次
        mTextTip.postDelayed(mRefreshMyChargeStateInfo, 10);
    }

    @Override
    public void onStop() {
        super.onStop();
        //移除请求
        mTextTip.removeCallbacks(mRefreshMyChargeStateInfo);
    }

    private Runnable mRefreshMyChargeStateInfo = new Runnable() {

        @Override
        public void run() {
            checkMyCharge();
        }
    };

    /**
     * 查询当前与充电有关的状态<br/>
     * <li>如果在预约状态，可以点击直接进入</li>
     * <li>如果在充电状态,公众号用户将进入充电列表选择某个充电查看</li>
     */
    private void checkMyCharge() {
        APIForCharge.getMyChargeInfo(new EHttpResponse() {

            @Override
            public void onEResponse(String response) {
                JsonChargeInfo result = GsonUtils.toBean(JsonChargeInfo.class, response);
                if (result != null && result.status == GlobalResult.OK.getStatus()) {
                    mPileSn = result.pileSn;
                    if (result.isCharging) {
                        showChargingText(result.userRole);
                    } else if (result.isBespeaking) {
                        showBespeakingText();
                    } else {
                        mTextTip.setVisibility(View.GONE);
                    }
                } else {
                    mPileSn = null;
                    mTextTip.setVisibility(View.GONE);
                }
            }
        });
    }

    private void showChargingText(int userRole) {
        mTextTip.setVisibility(View.VISIBLE);
        SpannableString span = new SpannableString(TIP_CHARGING);
        //你当前
        span.setSpan(new AbsoluteSizeSpan(14, true), 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(Color.rgb(147, 143, 95)), 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //正在充电
        span.setSpan(new AbsoluteSizeSpan(14, true), 3, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(Color.BLACK), 3, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //，
        span.setSpan(new AbsoluteSizeSpan(14, true), 7, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(Color.rgb(147, 143, 95)), 7, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //点此查看
        span.setSpan(new ChargingClickable(userRole), 8, 12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new AbsoluteSizeSpan(13, true), 8, 12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        mTextTip.setHighlightColor(Color.TRANSPARENT);
        mTextTip.setMovementMethod(LinkMovementMethod.getInstance());
        mTextTip.setText(span);
    }

    private void showBespeakingText() {
        mTextTip.setVisibility(View.VISIBLE);
        SpannableString span = new SpannableString(TIP_BESPEAKING);

        //你有一个
        span.setSpan(new AbsoluteSizeSpan(14, true), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(Color.rgb(147, 143, 95)), 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //充电预约
        span.setSpan(new AbsoluteSizeSpan(14, true), 4, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(Color.BLACK), 4, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //订单，
        span.setSpan(new AbsoluteSizeSpan(14, true), 8, 11, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(Color.rgb(147, 143, 95)), 8, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //点此查看
        span.setSpan(new BespeakingClickable(), 11, 15, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new AbsoluteSizeSpan(13, true), 11, 15, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        mTextTip.setHighlightColor(Color.TRANSPARENT);
        mTextTip.setMovementMethod(LinkMovementMethod.getInstance());
        mTextTip.setText(span);
    }

    private class ChargingClickable extends ClickableSpan {
       private int userRole;

        ChargingClickable(int userRole)  {
            this.userRole = userRole;
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setColor(Color.rgb(147, 143, 95));
            ds.setUnderlineText(true);
        }

        @Override
        public void onClick(View widget) {
            goToCharge(userRole);
        }
    }

    private void goToCharge(int userRole) {
        if (mPileSn == null) {
            Snackbar.make(mTextTip, "参数错误！", Snackbar.LENGTH_SHORT).show();
            return;
        }
        gotoChargeByUserRole(userRole);
    }

    private class BespeakingClickable extends ClickableSpan {

        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setColor(Color.rgb(147, 143, 95));
            ds.setUnderlineText(true);
        }

        @Override
        public void onClick(View widget) {
            goToBespeak();
        }
    }

    private void goToBespeak() {
        Intent intent = new Intent(mContext, ActivityMyBooking.class);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.textview_mycharge://我的充电
                gotoChargeByUserRole(AppContext.getInstance().getUserRole());
                break;
            case R.id.imageview_qrcode://扫码
                scanCode(CaptureActivity.INPUT_MODE_QR);
                break;
            case R.id.imageview_inputsn:
                scanCode(CaptureActivity.INPUT_MODE_TEXT);
                break;
            default:
                break;
        }
    }

    //扫码按钮
    private void scanCode(int mode) {
        AppContext appContext = AppContext.getInstance();
        if (appContext.isLogin()) {
            Intent intent = new Intent(getActivity(), CaptureActivity.class);
            intent.putExtra(CaptureActivity.KEY_INPUT_MODE, mode);
            startActivityForResult(intent, QR_CODE_REQUEST);
        } else {
            Intent intent = new Intent(mContext, ActivityLogin.class);
            startActivity(intent);
        }
    }

    private void gotoChargeByUserRole(int userRole) {
        if (userRole == JsonUser.ENTERPRISE_NUMBER_USER) {
            enterpriseCharge();
        } else {
            commonUserCharge();
        }
    }

    // 企业号用户充电查询，可多人充电
    private void enterpriseCharge() {
        Intent intent = new Intent(mContext, ActivityChargeList.class);
        startActivity(intent);
    }

    private void commonUserCharge() {
        mProgress = ProgressDialog.show(mContext, null, "正在读取...", true, true, new DialogInterface.OnCancelListener() {

                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (mRequest != null) {
                            mRequest.cancel();
                        }
                    }
                });
        //读取当前充电相关的消息
        mRequest = APIForCharge.refreshCharge(null, mResponseMyCharge);
    }

    /**
     * 查询 我的充电 的返回
     */
    EHttpResponse mResponseMyCharge = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonChargeRefresh result = GsonUtils.toBean(JsonChargeRefresh.class, response);
            if (handleResult(result)) {
                //判断 直流
                if (result.isDcCharging()) {
                    jumpToDcChargingActivity(result);
                    //判断 交流
                } else if (result.isAcCharging()) {
                    jumpToAcChargingActivity(result);
                } else {
                    Toast.makeText(mContext, "无法判断充电桩类型！", Toast.LENGTH_SHORT).show();
                }
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            Toast.makeText(mContext, "无法读取数据！", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onEFinish() {
            super.onEFinish();
            if (mProgress != null) {
                mProgress.dismiss();
            }
        }
    };

    private boolean handleResult(JsonChargeRefresh result) {
        if (result == null) {
            Toast.makeText(mContext, "无法解析数据！", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (result.status == GlobalResult.OK.getStatus()) {
          return true;

        } else if (result.status == GlobalResult.TOKEN_INVALID.getStatus()
                || result.status == GlobalResult.TOKEN_REQUIRED.getStatus()) {
            BaseActivity.jumpToLogin(getActivity(), false);

        } else if (result.status == GlobalResult.CHARGE_FINISH_OK.getStatus()) {
            //结账信息
            Log.e(TAG, "onEResponse: status" + result.status);

        } else {
            Toast.makeText(mContext, result.message, Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    private void jumpToDcChargingActivity(JsonChargeRefresh result) {
        Intent intent = new Intent(mContext, ActivityChargingDc.class);
        intent.putExtra("pileSn", result.pileSn);
        intent.putExtra("gunNum", result.gunNun);
        intent.putExtra(ActivityChargingDc.KEY_CHARGE_ACTION, ActivityChargingDc.CHARGE_ACTION_CHARGING);
        startActivity(intent);
    }

    private void jumpToAcChargingActivity(JsonChargeRefresh result) {
        Intent intent = new Intent(mContext, ActivityChargingAc.class);
        intent.putExtra("pileSn", result.pileSn);
        intent.putExtra("tariff", result.tariff);
        intent.putExtra("gunNum", result.gunNun);
        intent.putExtra(ActivityChargingAc.KEY_CHARGE_ACTION, ActivityChargingAc.CHARGE_ACTION_CHARGING);
        startActivity(intent);
    }

    private void showProgressDialog(String msg) {
        mProgressDialog = ProgressDialog.show(mContext, null, msg, true, true,
                new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        cancelRequest();
                    }
                });
        mProgressDialog.setCanceledOnTouchOutside(false);
    }

    private void dismissProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    private void cancelRequest() {
        if (mRequest != null) {
            mRequest.cancel();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == QR_CODE_REQUEST && resultCode == CaptureActivity.RESULT_CODE) {
            mSn = data.getStringExtra("sn");
            isSame = data.getBooleanExtra("isSame", false);
            if (mSn != null && (!"".equals(mSn))) {
                showProgressDialog("提交中...");
                mRequest = APIForCharge.qrScan(mSn, mResponse);
            } else {
                Log.e(TAG, "onActivityResult: sn " + data.getStringExtra("sn"));
            }
        }
    }

    private EHttpResponse mResponse = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonQrScan result = GsonUtils.toBean(JsonQrScan.class, response);
            if (result == null) {
                exceptionDialog("请输入正确的序列号");

            } else if (result.status == GlobalResult.TOKEN_INVALID.getStatus()) {
                Intent intent = new Intent(mContext, ActivityLogin.class);
                startActivity(intent);

            } else if (result.status == GlobalResult.OK.getStatus()) {
                if ((!isSame)) {
                    SharedPreferences userInfo = getActivity().getSharedPreferences(CaptureActivity.SHARED_KEY, Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = userInfo.edit();

                    editor.putString("pointSn", mSn);
                    editor.apply();
                }
                handleResult(result);

            } else {
                //继续扫描解码
                exceptionDialog("抱歉，" + result.message);
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            exceptionDialog("抱歉，无法获取服务器数据！");
        }

        @Override
        public void onEFinish() {
            super.onEFinish();
            dismissProgressDialog();
        }
    };

    private void handleResult(JsonQrScan result) {
        int gun = result.gunInfos.size();
        // 对比 预约桩与实际扫码得到的桩不一致
        if (result.compares != null) {
            jumpToChoosePileActivity();

        } else {
            // 判断当前桩是否连接服务器
            if (result.isConnect) {
                // 有地锁选择地锁
                if (result.isNeedOpenLock()) {
                    jumpToLockActivity(result);

                    // 是否为双枪充电桩
                } else if (result.isDoubleGun()) {
                    jumpToDoubleGunActivity(result);

                    // 是否为单枪充电桩
                } else if (result.isSingleGun()) {
                    jumpToSingleGunActivity(result);

                    // 是否为多枪充电桩
                }else if (gun > 2 || result.pileType == JsonPointPile.PILE_TYPE_DC_MULTI_GUN_SYN
                                  || result.pileType == JsonPointPile.PILE_TYPE_AC_MULTI_GUN_SINGLE_SYN
                                  || result.pileType == JsonPointPile.PILE_TYPE_AC_MULTI_GUN_THREE_SYN  ) {
                    jumpToMultiGunActivity(result);

                    // 未知的充电桩类型
                } else {
                    exceptionDialog("错误:未知的充电桩类型！");
                }
            } else {
                exceptionDialog(result.message);
            }
        }
    }

    private void jumpToSingleGunActivity(JsonQrScan result) {
        Intent intent = new Intent(mContext, ActivitySingleGun.class);
        intent.putExtra(JsonQrScan.KEY, result);
        startActivity(intent);
    }

    private void jumpToDoubleGunActivity(JsonQrScan result) {
        Intent intent = new Intent(mContext, ActivityDoubleGun.class);
        intent.putExtra(JsonQrScan.KEY, result);
        startActivity(intent);
    }

    private void jumpToMultiGunActivity(JsonQrScan result) {
        Intent intent = new Intent(mContext, ActivityMultiGun.class);
        intent.putExtra(JsonQrScan.KEY, result);
        startActivity(intent);
    }

    private void jumpToChoosePileActivity() {
        Intent intent = new Intent(mContext, ActivityChoosePile.class);
        Bundle bundle = new Bundle();
        bundle.putString(Const.KEY_PILE_SN, mSn);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void jumpToLockActivity(JsonQrScan result) {
        Intent intent = new Intent(mContext, ActivityLock.class);
        intent.putExtra(JsonQrScan.KEY, result);
        startActivity(intent);
    }

    private void exceptionDialog(String msg) {
        if (mDialog == null) {
            mDialog = new DialogResult(mContext, false, "电桩不可用", msg);
        } else {
            mDialog.setMsgText(msg);
        }
        mDialog.show();
    }

}
